package org.bmi.gwt.examples.chat.server;

import org.apache.log4j.Logger;
import org.bmi.gwt.examples.chat.shared.ChatConstants;
import org.bmi.gwt.examples.chat.shared.SenderProxy;
import org.bmi.gwt.mi.server.annotation.QueueHandler;
import org.bmi.gwt.mi.server.events.QueueEvent;
import org.bmi.gwt.mi.server.events.QueueEventHandler;
import org.bmi.gwt.mi.shared.BroadChannel;
import org.bmi.gwt.mi.shared.Channel;
import org.bmi.gwt.mi.shared.callbacks.AttributeCallback;
import org.bmi.gwt.mi.shared.communication.attribute.StringValue;
import org.bmi.gwt.mi.shared.exceptions.MiException;
import org.bmi.gwt.mi.shared.exceptions.NameParseException;

@QueueHandler(queueExpression = "org.bmi.gwt.mi.test.chat.*")
public class ChatQueueEventHandler implements QueueEventHandler
{
	static protected Logger logger = Logger.getLogger(ChatQueueEventHandler.class);

	@Override
	public void onCreate(QueueEvent event)
	{}

	@Override
	public void onBound(final QueueEvent event)
	{
		Channel queue = event.getSourceQueueChannel();
		queue.getAttribute("userName", new AttributeCallback<StringValue>()
		{
			@Override
			public void onError(MiException error)
			{
				logger.info("[ChatQueueEventHandler] impossible to get user name attribute:" + error);
			}

			@Override
			public void onSuccess(StringValue value)
			{
				try
				{
					event.setQueueSessionAttribute("userName", value.getValue());

					BroadChannel qSend = event.getBroadChannel("org.bmi.gwt.mi.test.chat.*");
					SenderProxy proxy = qSend.proxyToObject(SenderProxy.class, ChatConstants.MESSENGER_ID);

					proxy.printMessage(value + " has joined the chat");
				}
				catch (NameParseException e)
				{}
			}
		});
	}

	@Override
	public void onUpdate(QueueEvent event)
	{}

	@Override
	public void onDispose(final QueueEvent event)
	{
		Channel queueName = event.getSourceQueueChannel();

		queueName.getAttribute("userName", new AttributeCallback<StringValue>()
		{
			@Override
			public void onError(MiException error)
			{
				logger.info("[ChatQueueEventHandler] impossible to get user name attribute:" + error);
			}

			@Override
			public void onSuccess(StringValue value)
			{
				try
				{
					BroadChannel qSend = event.getBroadChannel("org.bmi.gwt.mi.test.chat.*");
					SenderProxy proxy = qSend.proxyToObject(SenderProxy.class, ChatConstants.MESSENGER_ID);

					proxy.printMessage(value + " has left the chat");
				}
				catch (NameParseException e)
				{}
			}
		});
	}
}
